package smashedapples.mvc
{
	import flash.events.Event;
	import flash.utils.getQualifiedClassName;

	import mx.events.PropertyChangeEvent;

	import smashedapples.core.NonVisualComponent;


	public class Controller extends NonVisualComponent
	{



		public function Controller( view:View = null )
		{
			super();
			if( view != null )
				this.$view = view;
		}

		public function addListeners( events:Array = null ):void
		{
			if( events == null || this.$view == null )
				return;

			for each( var event:String in events )
			{
				this.$view.addEventListener( event, execute, true );
			}
		}


		public function execute( event:Event ):void
		{
			if( event is PropertyChangeEvent )
				return this.handlePropertyChange( event as PropertyChangeEvent );

			var handlerName:String = getExecuteHandlerName( event );

			//if( $view.debug )
			trace( $view + ".controller." + handlerName + "(" + flash.utils.getQualifiedClassName( event ) + ")" );


			if( this.hasOwnProperty( handlerName ))
			{
				var method:Function = this[ handlerName ] as Function;
				method.apply( this, [ event ]);
			}
		}

		protected function getExecuteHandlerName( event:Event ):String
		{
			return "handle" + event.type.substr( 0, 1 ).toUpperCase() + event.type.slice( 1 );
		}


		private function handlePropertyChange( event:PropertyChangeEvent ):void
		{
			var handlerName:String = "handle" + event.property.substr( 0, 1 ).toUpperCase() + event.property.slice( 1 ) + "Change";

			/* trace(handlerName +  "(" + flash.utils.getQualifiedClassName(event) + ")"); */

			if( this.hasOwnProperty( handlerName ))
			{
				var method:Function = this[ handlerName ] as Function;
				method.apply( this, [ event ]);
			}

			return;
		}

		/* protected function handleMapEvent( event:Event ):void
		   {
		   var clazz:Class = mapEvents[ event.type ] as Class;
		   var handler:
		   }

		   public function mapEvent( type:String, clazz:Class ):void
		   {
		   this.mapEvents[type] = clazz;
		   this.addEventListener( type, handleMapEvent );
		   }

		 protected var mapEvents:Dictionary = new Dictionary(); */

		public var $view:View;


	}
}